﻿using NAudio.CoreAudioApi;

namespace TroubleshootingofBeanBagAssistant.lCheck
{

	public class AudioEndPointsCheck : IDiagnosticCheck
	{
		public string Name => "麦克风设备检测";

		public CheckResult Run()
		{
			try
			{
				MMDeviceEnumerator enumerator = new();
				var devices = enumerator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.Active).ToArray();

				if (devices.Length == 0)
				{
					return new CheckResult
					{
						Title = "未检测到可用麦克风设备",
						Detail = "请检查麦克风是否插好或已启用"
					};
				}

				MMDevice defaultDevice = enumerator.GetDefaultAudioEndpoint(DataFlow.Capture, Role.Console);

				bool foundAIMic = false;
				foreach (MMDevice device in devices)
				{
					if (device.DeviceFriendlyName.ToLower() == "unknown")
						continue;

					int result = MainWindowStaticHelper.GetIdByName(device.DeviceFriendlyName);

					// 检查系统默认麦克风
					if (device.DeviceFriendlyName == defaultDevice.DeviceFriendlyName)
					{
						if (result == 0)
						{
							foundAIMic = true;
							return new CheckResult
							{
								Title = "系统默认麦克风为AI设备",
								Detail = $"当前设备: {device.DeviceFriendlyName}"
							};
						}
						else
						{
							return new CheckResult
							{
								Title = "系统默认麦克风不是AI设备",
								Detail = $"当前设备: {device.DeviceFriendlyName}"
							};
						}
					}
				}

				// 如果没有任何AI设备
				bool hasAIMic = devices.Any(d => MainWindowStaticHelper.GetIdByName(d.DeviceFriendlyName) == 0);
				if (hasAIMic)
				{
					return new CheckResult
					{
						Title = "检测到AI麦克风，但未设为默认",
						Detail = "请在系统声音设置中将AI麦克风设为默认"
					};
				}
				else
				{
					return new CheckResult
					{
						Title = "未检测到AI麦克风",
						Detail = "请检查AI麦克风是否已正确连接"
					};
				}
			}
			catch (Exception ex)
			{
				return new CheckResult
				{
					Title = "麦克风检测异常",
					Detail = ex.Message
				};
			}
		}

		// 辅助静态类用于麦克风名称匹配
		public static class MainWindowStaticHelper
		{
			public static int GetIdByName(string name)
			{
				int ManufacturerID = -1;
				try
				{
					if (name.Contains("AiMouse"))
					{
						ManufacturerID = 0;
					}
				}
				catch
				{
					// 忽略异常
				}
				return ManufacturerID;
			}
		}
	}

}
